﻿#region License
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using MediaWiki.Common;

namespace MediaWiki.MediaWikiConverter.Utilities.Logging
{
  public static class EventLogUtils
  {
    public static void EnsureEventSourceExists(string source, string logName, string machineName)
    {
      string currentLogName = null;

      bool sourceExists = EventLog.SourceExists(source, machineName);
      if (sourceExists)
        currentLogName = EventLog.LogNameFromSourceName(source, machineName);

      if (sourceExists && currentLogName != logName)
      {
        Debug.WriteLine("Changing event source '{0}' from log '{1}' to log '{2}'".FormatWith(source, currentLogName, logName));

        EventLog.DeleteEventSource(source, machineName);
        CreateEventSource(source, logName, machineName);
      }
      else if (!sourceExists)
      {
        Debug.WriteLine("Creating event source Source '{0}' in log '{1}']".FormatWith(source, logName));

        CreateEventSource(source, logName, machineName);
      }
      else
      {
        Debug.WriteLine("Event source '{0}' already exists".FormatWith(source));
      }
    }

    public static void EnsureEventSourceRemoved(string source, string logName, string machineName)
    {
      bool sourceExists = EventLog.SourceExists(source, machineName);
      if (sourceExists)
      {
        Debug.WriteLine("Removing event source '{0}'".FormatWith(source));
        EventLog.DeleteEventSource(source, machineName);
      }
      else
      {
        Debug.WriteLine("Event source '{0}' already removed".FormatWith(source));
      }
    }

    private static void CreateEventSource(string source, string logName, string machineName)
    {
			EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(source, logName);
			eventSourceCreationData.MachineName = machineName;
			EventLog.CreateEventSource(eventSourceCreationData);
    }
  }
}